package org.insia.smartposse.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
import org.insia.smartposse.config.HibernateSessionFactory;
import org.insia.smartposse.dao.GenericDAO;

/** Filter for the Hibernate Session.
 * <p>
 * 	We activate the session when the application is launching
 * </p>
 * @author raguerri
 * @since 11 avr. 07
 * @version 0.0.1
 *
 */
public class HibernateSessionFilter implements Filter {

	private Logger log = Logger.getLogger(HibernateSessionFilter.class);


    /**
     * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
     */
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain)
    throws IOException, ServletException {
    	Transaction tx = null;
    	Session session = GenericDAO.get_SESSION();
        try {
        	
        	
        	log.info("Starting a database transaction");
        	tx = session.beginTransaction();

            // Call the next filter (continue request processing)
            chain.doFilter(request, response);
            
            // Commit and cleanup
            //log.info("Flushing");
            //session.flush();
            log.info("Committing the database transaction");
            tx.commit();
        } catch (StaleObjectStateException staleEx) {
        	staleEx.printStackTrace();
        	log.error("This interceptor does not implement optimistic concurrency control!");
            log.error("Your application will not work until you add compensation actions!");
            // Rollback, close everything, possibly compensate for any permanent changes
            // during the conversation, and finally restart business conversation. Maybe
            // give the user of the application a chance to merge some of his work with
            // fresh data... what you do here depends on your applications design.
            throw staleEx;
        } catch (Throwable ex) {
            // Rollback only
            ex.printStackTrace();
            try {
                if (tx.isActive()) {
                	log.info("Trying to rollback database transaction after exception");
                	tx.rollback();
                }
            } catch (Throwable rbEx) {
            	log.error("Could not rollback transaction after exception!", rbEx);
            }

            // Let others handle it... maybe another interceptor for exceptions?
            throw new ServletException(ex);
        }
        //session.close();
    }

    /**
     * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
     */
    public void init(FilterConfig filterConfig) throws ServletException {
    	log.info("Initializing filter...");
        log.info("Obtaining SessionFactory from static HibernateUtil singleton");
        HibernateSessionFactory.getSessionFactory();
   		GenericDAO.set_SESSION(HibernateSessionFactory.getSession());
    }

    /**
     * @see javax.servlet.Filter#destroy()
     */
    public void destroy() {}

}
